/*
 * Copyright (c) 2013-2015 Charkey. All rights reserved.
 *
 * This software is the confidential and proprietary information of Charkey.
 * You shall not disclose such Confidential Information and shall use it only
 * in accordance with the terms of the agreements you entered into with Charkey.
 *
 * Charkey MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT.
 *
 * Charkey SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING,
 * MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
 */

package cn.simastudio.talos.common.utils.codec;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * Message Authentication Code：消息认证码算法
 */
public class HmacSHA256Utils {

    public static final String ALGORITHM_NAME = "HmacSHA256";

    /**
     * HmacSHA256摘要算法
     *
     * @param secretKey 密钥
     * @param content   待计算内容
     * @return 消息摘要
     */
    public static String digest(String secretKey, String content) {
        try {
            byte[] secretByte = secretKey.getBytes("utf-8");
            byte[] dataBytes = content.getBytes("utf-8");
            // 还原密钥
            SecretKey secret = new SecretKeySpec(secretByte, ALGORITHM_NAME);
            // 实例化Mac
            Mac mac = Mac.getInstance(secret.getAlgorithm());
            //初始化Mac
            mac.init(secret);
            // 执行消息摘要
            byte[] doFinal = mac.doFinal(dataBytes);
            byte[] hexB = new Hex().encode(doFinal);
            return new String(hexB, "utf-8");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 产生HmacSHA256摘要算法的密钥
     *
     * @return keyByte
     * @throws NoSuchAlgorithmException
     */
    public static String initHmacSHA256Key() throws NoSuchAlgorithmException {
        // KeyGenerator类用于获得各类对称加密技术的密钥
        // 初始化HmacMD5摘要算法的密钥产生器，设置要获得的密钥的加密算法
        KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM_NAME);
        // 产生密钥，从对称加密的密钥对象中取得密钥
        SecretKey secretKey = generator.generateKey();
        // 获得密钥
        return Base64.encodeBase64String(secretKey.getEncoded());
    }

    public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        String secretKey = initHmacSHA256Key();
        System.out.println("SecretKey: " + secretKey);
        String contentForMac = "Charkey";
        System.out.println(digest(secretKey, contentForMac));
    }
}
